import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProTable,
} from '@ant-design/pro-components';
import {Button, Drawer, message} from 'antd';
import React, {useRef, useState} from 'react';
import UpdateForm from './components/UpdateForm';
import {
  addInterfaceInfo,
  deleteInterfaceInfos, listAllInterfaceInfoByPage, offlineInterface, onlineInterface,
  updateInterfaceInfo
} from "@/services/zoffyApi/interfaceInfoController";
import CreateForm from "@/pages/InterfaceInfo/components/CreateForm";

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.InterfaceInfoAddRequest) => {
  const hide = message.loading('正在添加');
  try {
    const res = await addInterfaceInfo({
      ...fields,
    });
    hide();
    if (res?.data) {
      message.success('添加成功');
      return true;
    } else {
      message.error('添加失败，请重试');
      return false;
    }
  } catch (error) {
    hide();
    message.error('添加失败，请重试');
    return false;
  }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.InterfaceInfoVo) => {
  const hide = message.loading('Configuring');
  try {
    const res = await updateInterfaceInfo(fields);
    hide();
    if (res.code == 0) {
      message.success('更新成功');
      return true;
    } else {
      message.error('更新失败，请重试');
      return false;
    }

  } catch (error) {
    hide();
    message.error('更新失败，请重试');
    return false;
  }
};

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.InterfaceInfoVo[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    const res = await deleteInterfaceInfos(selectedRows);
    hide();
    if (res.code == 0) {
      message.success('删除成功');
      return true;
    } else {
      message.error('删除失败，请重试');
      return false;
    }
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateVisible, handleUpdateVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.InterfaceInfoVo>();
  const [selectedRowsState, setSelectedRows] = useState<API.RuleListItem[]>([]);
  // const [requestParams, setRequestParams] = useState<JSON>(JSON.parse("{}"));

  const interfaceOnline = async (id: string) => {
    const res = await onlineInterface({
      idRequest: {
        id: id,
      }
    })
    if (!res.data) {
      message.error("操作失败");
      return;
    }
    message.success("接口上线成功");
    actionRef.current?.reloadAndRest?.();
  }

  const interfaceOffline = async (id: string) => {
    const res = await offlineInterface({
      idRequest: {
        id: id,
      }
    })
    if (!res.data) {
      message.error("操作失败");
      return;
    }
    message.success("接口下线成功");
    actionRef.current?.reloadAndRest?.();
  }


  const columns: ProColumns<API.InterfaceInfoVo>[] = [

    {
      title: '接口名称',
      dataIndex: 'name',
      valueType: "text",
    },
    {
      title: '描述',
      dataIndex: 'description',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '请求方法',
      dataIndex: 'method',
      valueType: "text",
      hideInSearch: true,
    },
    {
      title: 'url',
      dataIndex: 'url',
      valueType: "text",
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '请求参数',
      dataIndex: 'requestParams',
      valueType: "text",
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '请求头',
      dataIndex: 'requestHeader',
      valueType: "text",
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '响应头',
      dataIndex: 'responseHeader',
      valueType: "text",
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      hideInSearch: true,
      valueEnum: {
        0: {
          text: '关闭',
          status: 'Default',
        },
        1: {
          text: '运行中',
          status: 'Processing',
        },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleUpdateVisible(true);
            setCurrentRow(record);
          }}
        >
          修改
        </a>,
        record.status === 0 ?
          <Button type="link" key="online"
                  onClick={() => {
                    interfaceOnline(record?.id || "");
                  }}
          >上线</Button> :
          <Button type="link" key="offline" danger
                  onClick={() => {
                    interfaceOffline(record?.id || "");
                  }}
          >下线</Button>
        ,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.InterfaceInfoVo, API.InterfaceInfoQueryRequest>
        headerTitle={'接口信息'}
        params={{
          pageSize: 10,

        }}
        pagination={
          {
            pageSize: 10,
          }
        }
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined/> 新建
          </Button>,
        ]}
        //@ts-ignore
        request={
          async (params: any) => {
            const res = await listAllInterfaceInfoByPage({
              ...params,
              page: params.current,
            })
            if (res?.data) {
              return {
                data: res?.data?.records || [],
                success: true,
                total: res.data.total,
              }
            }
            return {};
          }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
              <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)} 万
              </span>
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
      <CreateForm onCancel={() => {
        handleModalVisible(false);
        if (!showDetail) {
          setCurrentRow(undefined);
        }
      }} onSubmit={
        async (value) => {
          const success = await handleAdd(value);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
          return true;
        }
      }
        updateModalVisible={createModalVisible} values={{}}/>
      <UpdateForm
        onSubmit={async (value) => {
          const id = currentRow?.id;
          const success = await handleUpdate({
            id: id,
            ...value,
          });
          if (success) {
            handleUpdateVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
          return true;
        }}
        onCancel={() => {
          handleUpdateVisible(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
          return true;
        }}
        updateModalVisible={updateVisible}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};
export default TableList;
